import { useData, useWeapp } from "@sker/runtime"
import { HttpError, encryptPassword, generateRandomString, toSuccess, useTransaction } from "@sker/core"
import { z } from "zod"
import { WxMGroup, WxMember } from "@sker/entities"

export default async () => {
    const input = z.object({
        mobile: z.string(),
        openid: z.string(),
        code: z.optional(z.string())
    })
    const body = input.parse(useData())
    await useTransaction(async m => {
        const app = await useWeapp();
        const wxMember = await m.findOne(WxMember, { where: { mobile: body.mobile }, select: { id: true } })
        if (wxMember) {
            throw new HttpError(`手机号已存在`)
        } else {
            const wxOpenidMember = await m.findOne(WxMember, { where: { openid: body.openid } })
            if (wxOpenidMember) {
                await m.update(WxMember, wxOpenidMember.id, {
                    mobile: body.mobile
                })
                return;
            }
            const wxGroup = await m.findOne(WxMGroup, { where: { is_default: true } })
            if (!wxGroup) throw new HttpError(`未设置默认会员组`)
            const password = generateRandomString(8)
            const salt = generateRandomString(8)
            const saltPassword = await encryptPassword(password, salt)
            await m.save(WxMember, {
                mobile: body.mobile,
                status: true,
                group_id: wxGroup.id,
                openid: body.openid,
                appid: app.getAppid(),
                permissions: {},
                password: saltPassword,
                salt: salt,
                online: true,
                code: body.code
            })
        }
    })
    return toSuccess(true)
}